package com.opc.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.WebSocketSession;  
import org.springframework.web.socket.CloseStatus;  
//import org.springframework.web.socket.annotation.EnableWebSocket;
//import org.springframework.web.socket.annotation.NotAllowed;
import javax.websocket.server.PathParam;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;  
import java.util.Set;  

@Component  
//@EnableWebSocket
@EnableWebSocketMessageBroker
public class MyWebSocketHandler extends TextWebSocketHandler {  

    private static Set<WebSocketSession> sessions = new HashSet<>();  

    @Override  
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {  
        sessions.add(session);  
        System.out.println("新连接: " + session.getId());  
    }  

    @Override  
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到消息: " + message.getPayload());  
    }  

    @Override  
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {  
        sessions.remove(session);  
        System.out.println("连接关闭: " + session.getId());  
    }  

    public void sendToAllClients(String message) throws IOException {
        for (WebSocketSession session : sessions) {  
            if (session.isOpen()) {  
                session.sendMessage(new TextMessage(message));  
            }  
        }  
    }  
}  